package com.lzx.adx.report.support.strategy.v3.channel;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.lzx.adx.report.annnotions.ProductType;
import com.lzx.adx.report.constant.ProductChannelConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.OcpxAccountDTO;
import com.lzx.adx.report.dto.ProductConfigDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.support.strategy.v2.channel.AbstractReport;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@ProductType(ProductChannelConstant.JYM)
public class JymReport extends AbstractProductReport {

    @Override
    public String execute(ReportDTO reportDTO, OcpxAccountDTO ocpxAccountDTO, ProductConfigDTO productConfigDTO) {
        Map<String, Object> prams = new HashMap<>();
        prams.put("os", "android");
        prams.put("ip", StringUtils.isNotBlank(reportDTO.getIp()) ? reportDTO.getIp() : "");
//        prams.put("ua", StringUtils.isNotBlank(reportDTO.getUser_agent()) ? URLUtil.encode(reportDTO.getUser_agent()) : "");
        prams.put("model", "");
        prams.put("ts",System.currentTimeMillis());

        prams.put("clickId",reportDTO.getBizRequestId());
        if(StringUtils.isNotBlank(reportDTO.getImei()) &&!StringUtils.contains(reportDTO.getImei(),"__")){
            prams.put("imei", reportDTO.getImei());
        }
        if(StringUtils.isNotBlank(reportDTO.getImeiSum()) &&!StringUtils.contains(reportDTO.getImeiSum(),"__")){
            prams.put("imeiMd5", reportDTO.getImeiSum());
        }
        if(StringUtils.isNotBlank(reportDTO.getOaid()) &&!StringUtils.contains(reportDTO.getOaid(),"__")){
            prams.put("oaid", reportDTO.getOaid());
        }
        if(StringUtils.isNotBlank(reportDTO.getOaidSum()) &&!StringUtils.contains(reportDTO.getOaidSum(),"__")){
            prams.put("oaidMd5", reportDTO.getOaidSum());
        }

        prams.put("callback", URLUtil.encode(productConfigDTO.getCallbackUrl()));
        String paramsUrl = URLUtil.buildQuery(prams, StandardCharsets.UTF_8);
        String finalUrl = ocpxAccountDTO.getReportUrl() + "&" + paramsUrl;

        log.info("账号为{},请求产品端的完整地址为 {}", ocpxAccountDTO.getId(), finalUrl);
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{} 请求产品端，响应的结果为{}", ocpxAccountDTO.getId(), body);

        ocpxAccountDTO.setFinalURL(finalUrl);
        return body;
    }
}
